#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/5/8
# @Author  : suk
# @File    : product.py
# @Software: PyCharm
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from common.API.res_josn_data import success_api, fail_api
from product.forms.product import ProductForm
from product.models import Product


class ProductPage(View):
    http_method_names = ['get']

    def get(self, request, *args, **kwargs):
        return render(request, 'product_manage/page.html')


class ProductList(View):
    http_method_names = ['get']

    def get(self, request, *args, **kwargs):
        count: int = Product.objects.count()
        product_objs = Product.objects.all()
        data_list = []
        for p in product_objs:
            data_list.append({
                'id': p.pk,
                'name': p.name,
                'specification': p.specification,
                'price': p.price,
                'quantity': p.quantity
            })
        return JsonResponse({
            "code": 0,
            "msg": "",
            "count": count,
            "data": data_list
        })


class ProductAdd(View):
    http_method_names = ['get', 'post']

    def get(self, request, *args, **kwargs):
        return render(request, 'product_manage/add.html')

    def post(self, request, *args, **kwargs):
        forms = ProductForm(data=request.POST)
        if forms.is_valid():
            forms.save()
            return success_api(msg='增加成功')


class ProductEdit(View):
    http_method_names = ['get', 'post']

    def get(self, request, *args, **kwargs):
        return render(request, 'product_manage/edit.html')

    def post(self, request, *args, **kwargs):
        product_obj = Product.objects.filter(pk=request.POST.get('id')).first()
        if not product_obj:
            return fail_api(msg='记录不存在')
        forms = ProductForm(instance=product_obj, data=request.POST)
        if forms.is_valid():
            forms.save()
            return success_api(msg='编辑成功')


class ProductDel(View):
    http_method_names = ['post']

    def post(self, request, *args, **kwargs):
        if request.POST.get('batch') == '0':
            Product.objects.filter(pk=request.POST.get('id')).delete()
        else:
            Product.objects.filter(pk__in=request.POST.getlist('id')).delete()
        return success_api(msg='删除成功')
